package com.liyunc.demo.base.component;

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JCheckBoxExample implements ActionListener{

    // 创建复选框
    JCheckBox checkBox01 = new JCheckBox("菠萝");
    JCheckBox checkBox02 = new JCheckBox("香蕉");
    JCheckBox checkBox03 = new JCheckBox("雪梨");
    JCheckBox checkBox04 = new JCheckBox("荔枝");
    JCheckBox checkBox05 = new JCheckBox("橘子");
    JCheckBox checkBox06 = new JCheckBox("苹果");

    JCheckBox checkBox =null;

    public void test() {
        JFrame jFrame = new JFrame("测试窗口");
        jFrame.setSize(250, 250);
        jFrame.setLocationRelativeTo(null);
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JPanel jPanel = new JPanel();



        // 添加第一个复选框的状态被改变的监听（其他复选框如果需要监听状态改变，则可按此方法添加监听）
        checkBox01.addActionListener(this);
        checkBox02.addActionListener(this);
        checkBox03.addActionListener(this);
        checkBox04.addActionListener(this);
        checkBox05.addActionListener(this);
        checkBox06.addActionListener(this);

        checkBox01.setSelected(true);//设置默认选中

        jPanel.add(checkBox01);
        jPanel.add(checkBox02);
        jPanel.add(checkBox03);
        jPanel.add(checkBox04);
        jPanel.add(checkBox05);
        jPanel.add(checkBox06);

        jFrame.setContentPane(jPanel);
        jFrame.setVisible(true);
    }

    public static void main(String[] args) {
        JCheckBoxExample jCheckBoxExample = new JCheckBoxExample();
        jCheckBoxExample.test();

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();
        if (checkBox01.equals(source) || checkBox02.equals(source) || checkBox03.equals(source) || checkBox04.equals(source) || checkBox05.equals(source) || checkBox06.equals(source)) {
            checkBox = (JCheckBox) e.getSource();
            System.out.println(checkBox.getText() + " 是否选中: " + checkBox.isSelected());
        }
    }
}
